<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <!-- 账号输入框 -->
                <el-form-item label="登陆账号" prop="account">
                    <el-input v-model="formData.account" :disabled="formData.root == 1" placeholder="请输入账号" clearable />
                </el-form-item>
                <el-form-item label="警号" prop="PersonalNo">
                    <el-input v-model="formData.PersonalNo" placeholder="请输入警号" clearable />
                </el-form-item>
                <!-- 管理员头像 -->
                <el-form-item label="头像">
                    <div>
                        <div>
                            <material-picker v-model="formData.avatar" :limit="1" />
                        </div>
                        <div class="form-tips">建议尺寸：100*100px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>

                <!-- 名称输入框 -->
                <el-form-item label="姓名" prop="realname">
                    <el-input v-model="formData.realname" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="formData.mobile" placeholder="请输入手机号" clearable />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="formData.gender" class="ml-4">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>

                </el-form-item>

                <el-form-item label="归属行政" prop="mydept">
                    <!-- multiple -->
                    <el-tree-select class="flex-1" v-model="formData.mydept" :data="optionsData.dept" node-key="id"
                        :current-node-key="formData.mydept" :render-after-expand="false" :props="{
            value: 'id',
            label: 'name',
            disabled: function (data: any, node: any) {//带子级的节点不能选中
                if (data.children && data.children.length > 0) {
                    return true
                } else {
                    return false
                }
            }
        }" check-strictly :default-expand-all="true" placeholder="请选择上级部门" />
                </el-form-item>
                <el-form-item label="查阅行政" prop="deptlist">
                    <!-- multiple -->
                    <el-tree-select class="flex-1" v-model="formData.deptlist" :data="optionsData.dept"
                        :default-expanded-keys="formData.deptlist" :render-after-expand="false" show-checkbox
                        node-key="id" :props="{
            value: 'id',
            label: 'name'
        }" :default-expand-all="true" placeholder="请选择可查询门" multiple />
                </el-form-item>
                <el-form-item label="归属党政" prop="partyid">
                    <!-- multiple -->
                    <el-tree-select class="flex-1" v-model="formData.partyid" :data="optionsData.party" node-key="id"
                        :current-node-key="formData.partyid" :render-after-expand="false" :props="{
            value: 'id',
            label: 'name',
            disabled: function (data: any, node: any) {//带子级的节点不能选中
                if (data.children && data.children.length > 0) {
                    return true
                } else {
                    return false
                }
            }
        }" check-strictly :default-expand-all="true" placeholder="请选择上级部门" />
                </el-form-item>
                <el-form-item label="查阅党政" prop="partlist">
                    <!-- multiple -->
                    <el-tree-select class="flex-1" v-model="formData.partylist" :data="optionsData.party"
                        :default-expanded-keys="formData.partylist" :render-after-expand="false" show-checkbox
                        node-key="id" :props="{
            value: 'id',
            label: 'name'
        }" :default-expand-all="true" placeholder="请选择可查询门" multiple />
                </el-form-item>
                <!-- <el-form-item label="岗位" prop="jobs_id">
                    <el-select
                        class="flex-1"
                        v-model="formData.jobs_id"
                        clearable
                        placeholder="请选择岗位"
                    >
                        <el-option
                            v-for="(item, index) in optionsData.jobs"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item> -->

                <!-- 角色选择框 -->
                <el-form-item label="角色" prop="role_id">
                    <el-select v-model="formData.role_id" :disabled="formData.root == 1" class="flex-1" multiple
                        placeholder="请选择角色" clearable>
                        <el-option v-if="formData.root == 1" label="系统管理员" :value="0" />
                        <el-option v-for="(item, index) in optionsData.role" :key="index" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="formData.password" show-password clearable placeholder="请输入密码" />
                </el-form-item>

                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="password_confirm">
                    <el-input v-model="formData.password_confirm" show-password clearable placeholder="请输入确认密码" />
                </el-form-item>

                <!-- 管理员状态 -->
                <el-form-item label="登陆状态" v-if="formData.root != 1">
                    <el-switch v-model="formData.disable" :active-value="0" :inactive-value="1" />
                </el-form-item>
                <!-- 多处登录 -->
                <!-- <el-form-item label="多处登录">
                    <div>
                        <el-switch
                            v-model="formData.multipoint_login"
                            :active-value="1"
                            :inactive-value="0"
                        />
                        <div class="form-tips">允许多人同时在线登录</div>
                    </div>
                </el-form-item> -->
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import { adminAdd, adminDetail, adminEdit } from '@/api/perms/admin'
import { roleAll } from '@/api/perms/role'
import { deptAll } from '@/api/org/department'
import { partyAll } from '@/api/org/party'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑管理员' : '新增管理员'
})
const formData = reactive({
    id: '',
    account: '',
    realname: '',
    mobile: '',
    gender: 1,
    PersonalNo: '',
    mydept: '',
    partyid: '',
    role_id: [],
    deptlist: [],
    partylist: [],
    avatar: '',
    password: '',
    password_confirm: '',
    disable: 0,
    multipoint_login: 1,
    root: 0
})
const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}
const formRules = reactive({
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    PersonalNo: [
        {
            required: true,
            message: '请输入警号',
            trigger: ['blur']
        }
    ],
    realname: [
        {
            required: true,
            message: '请输入姓名',
            trigger: ['blur']
        }
    ],
    role_id: [
        {
            type: 'array',
            required: true,
            message: '请选择角色',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[]
})
const { optionsData } = useDictOptions<{
    role: any[]
    dept: any[]
    party: any[]
}>({
    role: {
        api: roleAll
    },
    dept: {
        api: deptAll
    },
    party: {
        api: partyAll
    }
})
////子级只能单选, 系统没有使用，仅做备留 @check-change="handleCheckChange"
// const handleCheckChange = (data:any, checked:any)=>{
//     if (checked) {
//         this.menuOptions.id = data.id
//         this.$refs.tree.setCheckedKeys([data.id], true)
//     } else {
//         this.menuOptions.id = null
//     }
// }

const handleSubmit = async () => {
    await formRef.value?.validate()
    console.log('提交数据=', formData);
    mode.value == 'edit' ? await adminEdit(formData) : await adminAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (row: any) => {
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    const data = await adminDetail({
        id: row.id
    })
    console.log('用户基本数据', data);
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData
})
</script>
